package cn.jkgly.wxUser.controller;


import cn.jkgly.log.entity.WxUserLog;
import cn.jkgly.log.service.IWxUserLogService;
import cn.jkgly.utils.AuthUtil;
import cn.jkgly.wxUser.entity.Result;
import cn.jkgly.wxUser.entity.WxRelateAccount;
import cn.jkgly.wxUser.entity.WxUser;
import cn.jkgly.wxUser.entity.WxUserButton;
import cn.jkgly.wxUser.service.IWxRelateAccountService;
import cn.jkgly.wxUser.service.IWxUserButtonService;
import cn.jkgly.wxUser.service.IWxUserService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;


/**
 * 微信注册授权相关Controller
 */
@Controller
//@RequestMapping("/wx")
public class WxUserController {

    @Autowired
    IWxUserService wxUservice;
    @Autowired
    IWxUserLogService wxUserLogService;

    @Autowired
    IWxRelateAccountService wxRelateAccountService;
    @Autowired
    IWxUserButtonService wxUserButtonService;

    /**
     * 导航其实页面，提示用户是否连接到授权申请界面
     *
     * @return
     */
    @RequestMapping("/navigation")
    public String navigation() {
        return "/navigation";
    }

    /**
     * 导航到授权申请主页面，并可以根据权限展示不同的功能按钮
     *
     * @return
     */
    @RequestMapping("/register")
    public String register() {
        return "/register";
    }

    /**
     * 保存一个微信用户
     *
     * @param user
     * @return
     */
    @PostMapping(value = "/postone")
    @ResponseBody//这个注解意味着这个方法的返回值不是页面名称，而是同一次请求的返回体（也就是服务器返回给客户端的数据）
    public Result<?> postone(@RequestBody WxUser user) {
        user.setCreatetime(new Date());
        wxUservice.saveOrUpdate(user);
        System.out.println(user.getNickname());
        log(user.getOpenid(), "postone成功");
        return Result.ok(user);
    }

    /**
     * 根据openid返回用户实体，包含授权字段（微信端权限），供前端页面展示
     *
     * @param openid
     * @return
     */
    @GetMapping(value = "/getAuthorization")
    @ResponseBody//这个注解意味着这个方法的返回值不是页面名称，而是同一次请求的返回体（也就是服务器返回给客户端的数据）
    public Result<?> queryById(@RequestParam(name = "openid", required = true) String openid) {
        QueryWrapper<WxUser> queryWrapper = new QueryWrapper<WxUser>();
        queryWrapper.eq("openid", openid);
        WxUser user = wxUservice.getOne(queryWrapper);
        if (user != null) {
            if (user.getAuthorization() != null) {
                String[] buttons = user.getAuthorization().split("\\|");
                for (String button : buttons) {
                    QueryWrapper<WxUserButton> queryWrapper1 = new QueryWrapper<WxUserButton>();
                    queryWrapper1.eq("button_name", button);
                    WxUserButton wxUserButton = wxUserButtonService.getOne(queryWrapper1);
                    if (wxUserButton != null) {
                        user.getButton().add(wxUserButton);
                    }
                }
            }
            log(openid, "getAuthorization成功");
            return Result.ok(user);
        } else {
            log(openid, "未注册");
            return Result.error("用户未注册");
        }
    }

    /**
     * 返回微信关联用户账户密码
     *
     * @param openid
     * @return
     */
    @GetMapping(value = "/auth/getRelateAccount")
    @ResponseBody
    public Result<?> getAccount(@RequestParam(name = "openid", required = true) String openid,
                                @RequestParam(name = "appName", required = true) String appName) {
        System.out.println(openid);
        QueryWrapper<WxRelateAccount> queryWrapper = new QueryWrapper<WxRelateAccount>();
        queryWrapper.eq("openid", openid).eq("app_name", appName);
        WxRelateAccount relateAccount = wxRelateAccountService.getOne(queryWrapper);
        if (relateAccount == null) {
            return Result.error("用户未设置关联账户");
        } else {
            return Result.ok(relateAccount);
        }
    }

    /**
     * 生成二维码
     *
     * @param model
     * @return
     */
    @RequestMapping("/qrcode")
    public String qrcode(Model model) {
        return "/qrcode";
    }

    public void log(String _openid, String _even) {
        WxUserLog log = new WxUserLog();
        log.setCreatetime(new Date());
        log.setOpenid(_openid);
        log.setEventinfo(_even);
        wxUserLogService.save(log);
    }


    /**
     * 提供给vuetest项目的后端测试数据
     *
     * @return
     */
    @GetMapping(value = "/list")
    @ResponseBody
    public Result<?> queryPageList() {
        List<WxUser> list = wxUservice.list();
        return Result.ok(list);
    }

    @GetMapping(value = "/auth/getButtonList")
    @ResponseBody
    public Result<?> getButtenList() {
        List<WxUser> list = wxUservice.list();
        return Result.ok(list);
    }

    @GetMapping(value = "/auth/getUserList")
    @ResponseBody
    public Result<?> getUserList(String param, int current, int size) {
        QueryWrapper<WxUser> queryWrapper = new QueryWrapper<WxUser>();
        queryWrapper.like("username", param).or().like("phone_number", param);
        Page page = new Page(current, size);
        IPage<WxUser> iPage = wxUservice.page(page, queryWrapper);
        List<WxUser> list = wxUservice.list(queryWrapper);
        return Result.ok(iPage);
    }

    @GetMapping(value = "/auth/getWxButtons")
    @ResponseBody
    public Result<?> getWxButtons() {

        List<String> list = wxUserButtonService.getButtonName();
        return Result.ok(list);
    }

    @ResponseBody
    @PostMapping(value = "/auth/updateAuthorization")
    public Result<?> updateAuthorization(@RequestBody WxUser wxUser) {
        UpdateWrapper<WxUser> wxUserUpdateWrapper = new UpdateWrapper<>();
        wxUserUpdateWrapper.set("authorization", wxUser.getAuthorization()).eq("openid", wxUser.getOpenid());
        if (wxUservice.update(wxUserUpdateWrapper)) {
            return Result.ok();
        }
        return Result.error("失败");
    }

}
